﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Cit.CDE.Net.Module;
using Cit.CDE.Net.Service;
using System.Text;
using System.Xml;
using Cit.CDE.Net.Module.Commons;
using Module;
using Cit.CDE.Net.Service.ModuleFactory;
using cde.SystemCommon;
using UserControl;
using System.Net;
using System.Management;
using ConfigAndElse;

/// <summary>
/// Copyright (C)   jinggubang
/// FileName:        login.aspx.cs         
/// Author :         fengsen
/// CDT:             2011-12-14           
/// Version:         1.0.0.0                
/// Depiction:       登录    
/// </summary>
public partial class login : System.Web.UI.Page
{
    #region 变量
    /// <summary>
    /// 权限
    /// </summary>
    private string functions = string.Empty;
    /// <summary>
    /// 保存密码
    /// </summary>
    private string COOKIE_NAME = "COOKIE_REMEMBER";
    /// <summary>
    /// 用户名
    /// </summary>
    private string COOKIE_USER = "COOKIE_USER";
    /// <summary>
    /// 密码
    /// </summary>
    private string COOKIE_PWD = "COOKIE_PWD";

    #endregion
    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //IP登录检查
        //IPCheck();
        //SoftReg reg = new SoftReg();
        //string machineCode = reg.GetMachineCode();
        //string RegKey = reg.GetRegKey(machineCode);
        //bool s = reg.ChkRegKey("5GBA-RIYA-TBZZ-BYBU-UWUX");

        //Response.Write("MachineCode:\t" + machineCode + "<br/>");
       // Response.Write("RegKey:\t" + RegKey + "<br/>");
        //Response.Write("结果:\t" + s.ToString());

       
        //系统注册检查
        RegCheck();      

        user.Focus();
        if (!Page.IsPostBack)
        {
            HttpCookie cookie = Request.Cookies.Get(COOKIE_NAME);
            if (cookie != null)
            {
                //记住密码
                this.remember.Checked = true;
                string userValue = HttpUtility.UrlDecode(cookie.Values.Get(COOKIE_USER));
                string pwdValue = HttpUtility.UrlDecode(cookie.Values.Get(COOKIE_PWD));
                this.user.Value = userValue;
                this.pwd.Attributes["text"] = pwdValue;
                StringBuilder sbr = new StringBuilder();
                sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
                sbr.AppendFormat("SetPWS('{0}');{1}",pwdValue, Environment.NewLine);
                sbr.AppendFormat("</script>{0}", Environment.NewLine);
               Page.ClientScript.RegisterStartupScript(Page.GetType(), "Success_Back", sbr.ToString());
            }

            //流量统计代码
            //Session[MenuPage.WEB_STATE_CODE] = "http://s4.cnzz.com/stat.php?id=4819742&web_id=4819742";
        }
    }

    /// <summary>
    /// 取IP
    /// </summary>
    /// <returns></returns>
    private string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }

  
    /// <summary>
    /// IP登录检查
    /// </summary>
    private void IPCheck() {
        string ip = string.Empty;
        //取客户端IP
        ip = GetClientIP();
        if (!ip.StartsWith("127") && !ip.StartsWith("192"))
        {
            string em_Full_name = "";// WEBConstants.EM_GET_IPINFO;
            iEntityManager iem = CDEEMServiceFactory.getEMByFullName(em_Full_name);
            CDESearchCriteria sc = iem.CreateSearchCriteria();
            sc.addCondition("IPADDRESS", ip);
            sc.addCondition("STATE", "0");
            List<CDEEntity> list = iem.LoadEntity(sc);
            if (list.Count == 0)
            {
                //清空Session
                //Session.Clear();
                //Server.Transfer("IPError.aspx");
            }
        }    
    }

    /// <summary>
    /// 系统信息注册检查
    /// </summary>
    private void RegCheck() {
        //系统信息Entity名字
        string EM_FULL_NAME = WEBConstants.EM_SYS_MANAGE;
        CDEEntityManager sys_em = CDEEMFactory.getEMByFullName(EM_FULL_NAME);
        CDESearchCriteria sys_sc = new CDESearchCriteria(sys_em);
        sys_sc.addCondition("ID", "1");
        List<CDEEntity> listEntity = CDEService.LoadEntities(sys_em, sys_sc);
        //系统信息ID是否存在
        if (listEntity.Count > 0)
        {
            CDEEntity m_entity = listEntity[0];
            Sys_Info sysInfo = new Sys_Info(m_entity);           
            //系统信息存入Session
            Session[WEBConstants.SYS_INFO_SESSION_ID] = sysInfo;

            if (sysInfo.SYS_CODE == "")
            {
                Response.Redirect("~/main/admin/sysReg.aspx");
            }
        }    
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        

        LoginOprator login = doLogin(this.user.Value, this.pwd.Value);
        if (login != null)
        {
            //记住密码
            if (this.remember.Checked)
            {
                HttpCookie cookie = new HttpCookie(COOKIE_NAME);
                cookie.Values.Add(COOKIE_USER, HttpUtility.UrlEncode(this.user.Value));
                cookie.Values.Add(COOKIE_PWD, HttpUtility.UrlEncode(this.pwd.Value));
                //指定客户端脚本是否可以访问[默认为false] 
                cookie.HttpOnly = true;
                //指定统一的Path，比便能通存通取 
                cookie.Path = "/";
                //设置跨域,这样在其它二级域名下就都可以访问到了 
                //cookie.Domain = "citbj.com";               
                cookie.Expires = DateTime.Now.AddDays(1d);
                Response.AppendCookie(cookie);
            }
            else
            {
                //清除密码COOKIES
                Response.Cookies[COOKIE_NAME].Expires = DateTime.Now.AddDays(-1);
            }
            //Jshydj.JsGQJF();
            //Jshydj.RemindPastdueIntegral();
            Session[Cit.CDE.Net.Module.Commons.CDEConstants.SESSION_LOIN_OPRATOR] = login;
            Session[UserControl.MenuPage.SESSION_MENU] = getLoginUserMenuXmlNode(login);
            Session[UserControl.MenuPage.SESSION_CLIENT_AVAILHEIGHT] = availHeight.Value;
            Session[UserControl.MenuPage.SESSION_CLIENT_AVAILWIDTH] = availWidth.Value;
            Response.Redirect("index.aspx");//   
            //Server.Transfer("index.aspx");
        }
        else
        {
            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            sbr.AppendFormat("alert('用户名或密码错误！');{0}", Environment.NewLine);
            sbr.AppendFormat("</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Success_Back", sbr.ToString());
        }
    }


    /// <summary>
    /// 登录用户权限
    /// </summary>
    /// <returns></returns>
    public XmlNode getLoginUserMenuXmlNode(LoginOprator login)
    {
        XmlNode AllNode = ConfigAndElse.SystemFasade.getAllMenuXmlNode();

        functions = login.ROLE_ID__ROLE_FUNC;
        CheckMenu(AllNode);


        return AllNode;
    }


    /// <summary>
    /// 操作菜单XML
    /// </summary>
    /// <param name="AllNode"></param>
    public void CheckMenu(XmlNode AllNode)
    {
        XmlNodeList nodeList = AllNode.SelectNodes("Menu");//获取bookstore节点的所有子节点
        foreach (XmlNode xn in nodeList)//遍历所有子节点
        {
            XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型        
            string id = xe.GetAttribute("id");
            if (!isPriv(id))
            {
                AllNode.RemoveChild(xn);
            }
            else
            {
                CheckMenu(xn);
            }
        }

    }

    /// <summary>
    /// 登录验证
    /// </summary>
    /// <param name="denglm"></param>
    /// <param name="mim"></param>
    /// <returns></returns>
    public static LoginOprator doLogin(string denglm, string mim)
    {
        string em_Full_name = WEBConstants.LOGIN_EM_FULL_NAME;
        iEntityManager iem = CDEEMServiceFactory.getEMByFullName(em_Full_name);
        CDESearchCriteria sc = iem.CreateSearchCriteria();
        sc.addCondition("PSW", mim);
        sc.addCondition("USER_NAME", denglm);
        //0:有效,1:无效
        sc.addCondition("DEL_FLG", "0");

        List<CDEEntity> list = iem.LoadEntity(sc);

        if (list.Count != 1) return null;

        if (!denglm.Equals(list[0].get("USER_NAME"))) return null;

        LoginOprator oprator = new LoginOprator(list[0]);
       
        return oprator;
    }


    /// <summary>
    /// 是否有权限
    /// </summary>
    /// <returns></returns>
    private bool isPriv(string id)
    {
        bool result = false;
        if (functions != null)
        {
            string[] func = functions.Split(",".ToCharArray());
            for (int i = 0; i < func.Length; i++)
            {
                if (id.Equals(func[i]))
                {
                    return true;
                }
                else
                {

                    string temp = division(func[i]);
                    string[] temparr = temp.Split(",".ToCharArray());
                    for (int k = 0; k < temparr.Length; k++)
                    {
                        if (temparr[k].Equals(id))
                        {
                            return true;
                        }
                    }
                }
            }

        }
        return result;
    }

    /// <summary>
    /// 拆分字符串
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    private string division(string s)
    {
        string b = "";
        string c = "";
        for (int i = 0; i < s.Length; i++)
        {
            b = b + s[i];
            c = c + b + ",";
        }
        return c;
    }

}
